import {
  ALL,
  Body,
  Controller,
  Get,
  Inject,
  Param,
  Post,
  Provide,
  Query,
  Rule,
  RuleType,
  Validate,
} from '@midwayjs/decorator';
import { Context } from 'egg';
import { Result } from '../Result';
import * as fs from 'fs';
import * as path from 'path';
import { CustomError } from '../middleware/customError';
import { createToken } from '../util/JwtUtil';
import { userLoginDTO } from '../DTO/User';
import { UserService } from '../service/user';

@Provide()
@Controller('/user', { tagName: '用户模块' })
export class UserController {
  @Inject()
  ctx: Context;

  @Inject()
  userService: UserService;

  @Get('/userInfo/:id')
  async getUserInfo(@Param('id') id: number) {
    return Result.success(id);
  }

  @Post('/login', { description: '登录接口' })
  @Validate(true)
  async login(@Body(ALL) user: userLoginDTO) {
    const userId = await this.userService.login(user);

    const token = createToken(userId, this.ctx.app.config.jwt.secret);

    return Result.success(token);
  }

  @Post('/upload')
  async upload(@Body() dataId: number, @Body() name: string) {
    for (let file of this.ctx.request.files) {
      try {
        fs.copyFileSync(file.filepath, `./nginx_files/${file.filename}`);
        console.log(file.filename);
      } catch (error) {
        console.log(error);
      } finally {
        fs.unlinkSync(file.filepath);
      }
    }

    return Result.success(name);
  }
}
